package com.gooluke.localcache.aop;

import com.gooluke.localcache.annotation.LocalCacheEvict;
import com.gooluke.localcache.cache.LocalCacheManager;
import com.gooluke.localcache.utils.SpELUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

@Aspect
@AllArgsConstructor
@Slf4j
public class LocalCacheEvictAspect {

    private final LocalCacheManager cacheManager;

    @Around("@annotation(localCacheEvict)")
    public Object cacheMethod(ProceedingJoinPoint joinPoint, LocalCacheEvict localCacheEvict) throws Throwable {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取方法的全路径限定名（包括包名、类名和方法名）
        String methodName = signature.getMethod().toString();
        // 构建缓存键
        String cacheKey = (localCacheEvict.key() != null && !localCacheEvict.key().isEmpty()) ? SpELUtil.parseSpEl(localCacheEvict.key(), joinPoint) : methodName;
        //删除缓存
        cacheManager.deleteCache(cacheKey);
        return joinPoint.proceed();
    }
}